var dragArea = document.getElementById('drag-area');
var photoImg = document.getElementById('photo');
var cropCircle = document.getElementById('crop-circle');
var circleCenter = document.getElementById('circle-center');
var cloneContainer = document.getElementById('clone-container');
var previewBtn = document.getElementById('preview-btn');
var scaleSlider = document.getElementById('scale-slider');
var scaleInput = document.getElementById('scale-input');
var scaleReset = document.getElementById('scale-reset');

var area = {}, photo = {
  translate: {
    x: 0, y: 0
  }, 
  transformOrigin: {
    x: 0, y: 0
  }
};

function readURL(input) {
  if (input.files && input.files[0]) {
    var file = input.files[0];
    var maxSizeInBytes = 3 * 1024 * 1024; // 设置最大文件大小为3MB

    if (file.size > maxSizeInBytes) {
      alert('文件超过限制大小，请选择较小的文件。');
      input.value = '';
      return;
    }

    var reader = new FileReader();
    reader.onload = function(e) {
      photoImg.src = e.target.result;
    }
    reader.readAsDataURL(file);
  }
}

$("#imageUpload").change(function() {
  readURL(this);
});

// 设置photoImg的top和left值为cropCircle的偏移值
photoImg.style.top = cropCircle.offsetTop + 'px';
photoImg.style.left = cropCircle.offsetLeft + 'px';

// 重置photoImg的变换属性
photoImg.style.transform = 'scale(1) rotate(0deg) translate(0px, 0px)';
photoImg.style.transformOrigin = '0px 0px';

// 当photoImg加载完成时触发的回调函数
photoImg.onload = function() {
  // 如果photoImg的自然宽度小于自然高度，则将其宽度设置为cropCircle的客户端宽度
  if (photoImg.naturalWidth < photoImg.naturalHeight) {
    photoImg.width = cropCircle.clientWidth;
  }
  // 如果photoImg的自然宽度大于自然高度，则将其高度设置为cropCircle的客户端高度
  else if (photoImg.naturalWidth > photoImg.naturalHeight) {
    photoImg.height = cropCircle.clientHeight;
  }
  // 如果photoImg的自然宽度等于自然高度，则将其宽度和高度都设置为cropCircle的客户端宽度和高度
  else {
    photoImg.height = cropCircle.clientHeight;
    photoImg.width = cropCircle.clientWidth;
  }
};

/*
circleCenter.style.top = cropCircle.offsetTop + (cropCircle.clientHeight / 2)+'px';
circleCenter.style.left = cropCircle.offsetLeft + (cropCircle.clientWidth / 2)+'px';
*/

dragArea.onmouseenter = function() {
  this.onmousedown = function(e) {
    var transform = photoImg.style.transform;
    var photoStyle = window.getComputedStyle(photoImg);
    var photoMatrix = new DOMMatrix(photoStyle.transform);
    var transformOrigin = photoImg.style.transformOrigin.replace(/px/g, '').split(' ');
  
    photo = {
      translate: {},
      x: photoMatrix.m41,
      y: photoMatrix.m42,
      scale: Number(/scale\((-?\d+(?:\.\d*)?)\)/.exec(transform)[1]),
      rotate: Number(/rotate\((-?\d+(?:\.\d*)?)deg\)/.exec(transform)[1]),
      transformOrigin: {
        x: Number(transformOrigin[0]),
        y: Number(transformOrigin[1])
      }
    }

    area = {
      start: {
        x: e.offsetX + (e.target == cropCircle ? cropCircle.offsetLeft : 0),
        y: e.offsetY + (e.target == cropCircle ? cropCircle.offsetTop : 0)
      },
      distance: {
        x: 0,
        y: 0
      }
    };

    this.onmousemove = function(e) {
      area.stop = {
        x: e.offsetX + (e.target == cropCircle ? cropCircle.offsetLeft : 0),
        y: e.offsetY + (e.target == cropCircle ? cropCircle.offsetTop : 0)
      };

      if (area.stop.x > area.start.x) {
        area.distance.x = {
          type: 'positive', // right
          total: area.stop.x - area.start.x
        }
      } else {
        area.distance.x = {
          type: 'negative', // left
          total: area.start.x - area.stop.x
        }
      }
      if (area.stop.y > area.start.y) {
        area.distance.y = {
          type: 'positive', // down
          total: area.stop.y - area.start.y
        }
      } else {
        area.distance.y = {
          type: 'negative', // up
          total: area.start.y - area.stop.y
        }
      }

      if (area.distance.x.type == 'positive') {
        photo.translate.x = photo.x + area.distance.x.total;
      } else {
        photo.translate.x = photo.x - area.distance.x.total;
      }
      if (area.distance.y.type == 'positive') {
        photo.translate.y = photo.y + area.distance.y.total;
      } else {
        photo.translate.y = photo.y - area.distance.y.total;
      }
      
      var photoRect = photoImg.getBoundingClientRect();
      var centerRect = circleCenter.getBoundingClientRect();
      var originX = (centerRect.left + 0.5) - photoRect.left;
      var originY = (centerRect.top + 0.5) - photoRect.top;
      var centerX = 0 - photoRect.width / 2;
      var centerY = 0 + photoRect.height / 2;
      var radians = photo.rotate * Math.PI / 180;
      var cos = Math.cos(radians);
      var sin = Math.sin(radians);
      var newX = (originX * cos) - (originY * sin);
      var newY = (originX * sin) - (originY * cos);
      // console.log('axisX', originX / photo.scale, 'axisY', originY / photo.scale);
      //console.log('newX', newX, 'newY', newY);
      /*
      photo.transformOrigin = {
        x: originX / photo.scale,
        y: originY / photo.scale
      }
      */
      photoTransform({x: photo.translate.x, y: photo.translate.y});
    }
  }
}

dragArea.onmouseleave = function() {
  this.onmousemove = function(e) {
    e.preventDefault();
  }
}

dragArea.onmouseup = function() {
  this.onmousemove = function(e) {
    e.preventDefault();
  }
}

// resetAll.onclick = function() {
//   scaleSlider.value = scaleReset.value;
//   scaleInput.value = scaleReset.value;
//   rotateSlider.value = rotateReset.value;
//   rotateInput.value = rotateReset.value;
//   photo = {
//     translate: {
//       x: 0, y: 0
//     },
//     transformOrigin: {
//       x: 0, y: 0
//     }
//   };
//   photoTransform({scale: 1, rotate: '0', x: '0', y: '0'});
//   photoPreview && photoPreview.remove();
// }

previewBtn.onclick = function() {
  if (!photoImg){
    alert("文件不能为空！");
    return;
  }
  var scaleFactor = 1;
  var qualityFactor = 2;
  var clone = photoImg.cloneNode();
  var transform = clone.style.transform;
  var transformOrigin = clone.style.transformOrigin.replace(/px/g, '').split(' ');
  var transformOriginX = transformOrigin[0] * scaleFactor;
  var transformOriginY = transformOrigin[1] * scaleFactor;
  clone.style.transformOrigin = transformOriginX+'px '+transformOriginY+'px '+transformOrigin[2]+'px';
  clone.style.transform = transform.replace(/translate\((-?\d+(?:\.\d*)?)px, (-?\d+(?:\.\d*)?)px\)/, function(translate, x, y) {
    return translate.replace(x, x * scaleFactor).replace(y, y * scaleFactor);
  });
  cloneContainer.append(clone);
  clone.id = 'photo-clone';
  html2canvas(clone, {
    logging: false,
    scale: qualityFactor,
    width: cropCircle.clientWidth * scaleFactor,
    height: cropCircle.clientHeight * scaleFactor
  }).then(function(canvas) {
    document.getElementById('photo-clone').remove();
    canvas.toBlob(function(blob) {
      var formData = new FormData();
      formData.append('image', blob, 'screenshot.jpg');
      $.ajax({
        url: '/account/uploadImage',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
          console.log('文件上传成功');
          // 处理上传成功后的逻辑
        },
        error: function(xhr, status, error) {
          console.error('文件上传失败');
          // 处理上传失败后的逻辑
        }
      });
    }, 'image/jpeg');
  });
}
// previewBtn.onclick = function() {
//   var scaleFactor = 1;
//   var qualityFactor = 2;
//   var clone = photoImg.cloneNode();
//   var transform = clone.style.transform;
//   var transformOrigin = clone.style.transformOrigin.replace(/px/g, '').split(' ');
//   var transformOriginX = transformOrigin[0] * scaleFactor;
//   var transformOriginY = transformOrigin[1] * scaleFactor;
//   clone.style.transformOrigin = transformOriginX+'px '+transformOriginY+'px '+transformOrigin[2]+'px';
//   clone.style.transform = transform.replace(/translate\((-?\d+(?:\.\d*)?)px, (-?\d+(?:\.\d*)?)px\)/, function(translate, x, y) {
//     return translate.replace(x, x * scaleFactor).replace(y, y * scaleFactor);
//   });
//   cloneContainer.append(clone);
//   clone.id = 'photo-clone';
//   html2canvas(clone, {
//     logging: false,
//     scale: qualityFactor,
//     width: cropCircle.clientWidth * scaleFactor,
//     height: cropCircle.clientHeight * scaleFactor
//   }).then(function(canvas) {
//     document.getElementById('photo-clone').remove();
//     if (!document.body.contains(photoPreview)) {
//       var image = document.createElement('img');
//       image.id = 'photo-preview';
//       previewContainer.append(image);
//       photoPreview = image;
//     }
//     photoPreview.src = canvas.toDataURL('image/jpeg');
//   });
// }

scaleSlider.oninput = function() {
  var value = this.value;
  scaleInput.value = value;
  photoTransform({scale: value});
}
scaleInput.oninput = function() {
  var value = this.value;
  this.value = value.length ? value : scaleReset.value;
  scaleSlider.value = this.value;
  photoTransform({scale: this.value});
}
scaleInput.onkeydown = function(e) {
  if (e.keyCode == 13) this.blur();
}
scaleInput.onblur = function() {
  var value = this.value;
  this.value = value.length ? value : scaleReset.value;
  scaleSlider.value = this.value;
  photoTransform({scale: this.value});
}
scaleReset.onclick = function() {
  scaleSlider.value = this.value;
  scaleInput.value = this.value;
  photoTransform({scale: this.value});
}

// rotateSlider.oninput = function() {
//   var value = this.value;
//   rotateInput.value = value;
//   photoTransform({rotate: value});
// }
// rotateInput.oninput = function() {
//   var value = this.value;
//   this.value = value.length ? value : rotateReset.value;
//   rotateSlider.value = this.value;
//   photoTransform({rotate: this.value});
// }
// rotateInput.onkeydown = function(e) {
//   if (e.keyCode == 13) this.blur();
// }
// rotateInput.onblur = function() {
//   var value = this.value;
//   this.value = value.length ? value : rotateReset.value;
//   rotateSlider.value = this.value;
//   photoTransform({rotate: this.value});
// }
// rotateReset.onclick = function() {
//   rotateSlider.value = this.value;
//   rotateInput.value = this.value;
//   photoTransform({rotate: this.value});
// }

function photoTransform(property) {
  property = property || {};
  var originX = 0, originY = 0;
  var transform = photoImg.style.transform;
  var axisX = property.axisX || photo.transformOrigin.x || (cropCircle.getBoundingClientRect().width / 2);
  var axisY = property.axisY || photo.transformOrigin.y || (cropCircle.getBoundingClientRect().height / 2);
  var scale = property.scale || photo.scale || Number(/scale\((-?\d+(?:\.\d*)?)\)/.exec(transform)[1]);
  var rotate = property.rotate || photo.rotate || Number(/rotate\((-?\d+(?:\.\d*)?)deg\)/.exec(transform)[1]);
  var translate = /translate\((-?\d+(?:\.\d*)?)px, (-?\d+(?:\.\d*)?)px\)/.exec(transform);
  var translateX = (property.x || photo.translate.x || Number(translate[1])) / scale;
  var translateY = (property.y || photo.translate.y || Number(translate[2])) / scale;
  
  photoImg.style.transformOrigin = axisX+'px '+axisY+'px';
  //photoImg.style.transform = 'scale('+scale+') rotate('+rotate+'deg) translate('+translateX+'px, '+translateY+'px)';
  photoImg.style.transform = 'scale('+scale+') translate('+translateX+'px, '+translateY+'px) rotate('+rotate+'deg)';
  
  photo.transformOrigin = {
    x: axisX,
    y: axisY
  }
  photo.scale = scale;
  photo.rotate = rotate;
}
